package com.ah.hf.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.sql.SQLIntegrityConstraintViolationException;

@ControllerAdvice(annotations = {RestController.class, Controller.class})
@Slf4j
@ResponseBody
//全局异常处理类
public class GlobalExceptionHandler {

    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> exceptionHandler(SQLIntegrityConstraintViolationException e){
        log.info(e.getMessage());

        //异常判断
        if (e.getMessage().contains("Duplicate entry")){
            //分割自字符串，转换成数组
            String[] element = e.getMessage().split(" ");
            //取得名字
            String el = element[2];
            //去掉字符串中的 '
            String s = el.replaceAll("'", "");
            log.info("当前名字是：{}",s);
            return R.error(s+"已经存在,请重新输入");
        }
        //抛处异常信息
        return R.error("添加失败");
    }

    @ExceptionHandler(CustomException.class)
    public R<String> CustomException(CustomException e){
        log.info(e.getMessage());

        //抛处异常信息
        return R.error(e.getMessage());
    }
}
